package org.zero.onlinesubject.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.zero.onlinesubject.entity.LiveRoom;
import org.zero.onlinesubject.entity.SystemFile;
import org.zero.onlinesubject.mapper.LiveRoomMapper;
import org.zero.onlinesubject.mapper.SystemFileMapper;
import org.zero.onlinesubject.service.LiveRoomService;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ScheduleUtil {

    private boolean flag = false;

    @Value("${file.external_path}")
    private String externalPath;

    @Resource
    private LiveRoomMapper liveRoomMapper;

    @Resource
    private SystemFileMapper systemFileMapper;

    // 每三个月的夜里三点，删除三个月前的聊天记录
    // 秒 分 时 日 月 周 年
    @Scheduled(cron = "0/30 * * * * ?")
    public void exec(){
        Iterator<Session> iterator = SessionContext.getSessions().iterator();
        while(iterator.hasNext()){
            try{
                iterator.next().getBasicRemote().sendText("Pong");
            }catch(Exception ex){
                log.info("有一个客户端已下线");
                iterator.remove();
            }
        }
        if(!flag){
            log.info("心跳检查机制开始执行。。。");
            flag = true;
        }
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void updateLiveState(){
        log.info("直播状态检测机制开始执行。。。");
        QueryWrapper<LiveRoom> wrapper = new QueryWrapper<>();
        wrapper.select("LiveID","LiveState","StartDate","EndDate").ne("LiveState","0003");
        List<LiveRoom> liveRooms = liveRoomMapper.selectList(wrapper);

        if(liveRooms.isEmpty()){
            return;
        }

        List<String> idList = liveRooms.stream().map(LiveRoom::getLiveid).collect(Collectors.toList());
        if(idList.isEmpty()) return;
        List<SystemFile> files = systemFileMapper.selectByBizIDs(idList);
        Map<String, String> map = files.stream().collect(Collectors.toMap(SystemFile::getBizid, SystemFile::getFilepath));

        liveRooms.stream().forEach(room->{
            String code = getLiveStateCode(room.getStartdate(),room.getEnddate());
            room.setLivestate(code);
            room.setLivelink(map.get(room.getLiveid()));
        });

        liveRooms.forEach(room->{
            UpdateWrapper<LiveRoom> wrapper2 = new UpdateWrapper<>();
            wrapper2.set("LiveState",room.getLivestate()).eq("LiveID",room.getLiveid());
            liveRoomMapper.update(wrapper2);
        });
    }

    private String getLiveStateCode(LocalDateTime begin, LocalDateTime end){
        LocalDateTime now = LocalDateTime.now();
        if(now.isBefore(begin)){
            return "0001";
        }else if(now.isBefore(end)){
            return "0002";
        }else{
            return "0003";
        }
    }
}
